package com.lovezy.platform.filestore.controller;

import com.lovezy.platform.core.base.Response;
import com.lovezy.platform.core.exception.BaseRuntimeException;
import com.lovezy.platform.core.jwt.JwtUtil;
import com.lovezy.platform.filestore.model.File;
import com.lovezy.platform.filestore.model.QiniuCallBackBody;
import com.lovezy.platform.filestore.oss.OssBucket;
import com.lovezy.platform.filestore.oss.OssBucketChooser;
import com.lovezy.platform.filestore.service.FileService;
import com.lovezy.platform.filestore.vo.FileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static com.lovezy.platform.core.base.Response.ok;
import static com.lovezy.platform.core.utils.ObjectUtil.copyTo;

/**
 * Created by jin on 2018/1/21.
 */
@RestController
@RequestMapping("/open/upload")
public class QiniuCallbackController {

    @Autowired
    FileService fileService;

    @Autowired
    OssBucketChooser ossBucketChooser;

    @RequestMapping("/qiniuCallback")
    public ResponseEntity<Response> qiniuCallback(@RequestBody QiniuCallBackBody body) {
        File file = saveInFile(body);
        FileVo fileVo = copyTo(file, new FileVo());
        return new ResponseEntity<>(ok(fileVo), HttpStatus.CREATED);
    }

    //TODO 优化锁
    private synchronized File saveInFile(QiniuCallBackBody body) {
        String fileKey = body.getFileKey();
        try {
            return fileService.findFileByUrl(fileKey);
        } catch (BaseRuntimeException e) {
            //ignore
        }
        File file = new File();
        file.setName(body.getName());
        OssBucket ossBucket = ossBucketChooser.bucketNameOf(body.getDir());
        file.setDir(ossBucket.getBucket());
        file.setUrl(fileKey);
        file.setContentType(body.getMimeType());
        file.setSize(body.getSize());
        String userToken = body.getUserToken();
        if (StringUtils.hasText(userToken)) {
            Map<String, Object> tokenMap = JwtUtil.parserJavaWebToken(userToken);
            Object mid = tokenMap.get("mid");
            if (mid != null) {
                file.setCreateId(String.valueOf(mid));
            }
        }
        fileService.saveFile(file);
        return file;
    }

}
